<template>

  <el-container style="overflow: hidden; height: 100%; width: 100%; ">

    <el-header height="auto" style=" border-bottom: 1px solid #060f1a12; ">
      <api-header></api-header>
    </el-header>

    <el-container class="appi-body-contaniner" style="overflow-y: scroll; overflow-x: hidden;">


      <div class="api-body-contaniner">
        <div style="text-align: right;">
          <el-button type="primary" icon="el-icon-check" @click="submitForm()">保存配置</el-button>
          <el-button @click="$jump('/app_info')" style="margin-left: 10px;">返 回</el-button>
        </div>
        <el-form ref="formEl" :rules="rules" :model="formValue" label-width="140px" style="width: 100%;">
          <field-title title="应用参数信息"></field-title>
          <el-row>
            <el-col>
              <el-form-item label="应用名称" prop="appName">
                <el-input v-model="formValue.appName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item label="应用类型" prop="appType">
                <el-select v-model="formValue.openAppType" placeholder="请选择" disabled>
                  <el-option key="ERP" label="ERP" value="ERP"></el-option>
                  <el-option key="WMS" label="WMS" value="WMS"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item label="appId">
                <span style="padding-left: 8px; color: #606266">{{ appId }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item label="appSecret">
                <span style="padding-left: 8px; color: #606266">{{ formValue.appSecret }}</span>
                <el-button type="text" @click="$copyToClip(formValue.appSecret, 'appSecret 已复制至剪切板')"
                style="margin-left: 20px;">复制</el-button>
              <el-button type="text" @click="generateRandomSecret" style="margin-left: 10px;">重新生成</el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 6px;">
            <el-col>
              <el-form-item label="通信地址" prop="callbackUrl" style="margin-bottom: 6px;">
                <el-input v-model="formValue.callbackUrl"></el-input>
                <span style="color: #666;"><i class="el-icon-warning"></i> ERP、WMS 用于接收 KYB 接口请求的地址，需以 http/https 开头</span>
              </el-form-item>
            </el-col>
          </el-row>

          <field-title title="应用接口配置"></field-title>

          <el-row>
            <el-col>
              <el-form-item label="" class="api-choose-label">
                <div style="color: #666;"><i class="el-icon-warning"></i> 如需开放新的接口，请联系管理员</div>
              </el-form-item>
            </el-col>
          </el-row>
          <template v-for="group, modelIndex in apiRoot">
            <el-row>
              <el-col>
                <el-form-item label-width="0" class="api-choose-label">
                  <table class="api-choose-table" cellspacing="1" cellpadding="1">

                    <template v-for="doc, docIndex in group.children">
                      <tr>
                        <td v-if="docIndex == 0" :rowspan="group.children.length" class="choose-table-group-td">
                          {{ group.name }}
                        </td>
                        <td class="choose-table-api-td">
                          <div :class="doc._checked_ ? 'active-div' : 'unactive-div'">
                            {{ doc.apiName }}
                            <span v-if="doc.apiType == 'ResponseApi'" class="api-notify-tag">通知</span>
                          </div>
                          <div style="color: green;" v-if="doc._checked_">
                            <i class="el-icon-check"></i> 已开启
                          </div>
                        </td>
                      </tr>
                    </template>

                  </table>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>

      </div>

    </el-container>




  </el-container>

</template>

<script>

import NavMenu from './api_sub/api-menu.vue'

import ApiItem from './api_sub/api-item.vue'

import ApiPortal from './api_sub/api-portal.vue'

import ApiConfig from './api_sub/api-config.vue'

import ApiLog from './api_sub/api-log.vue'

import ApiDoc from './api_sub/api-doc.vue'

import ApiHeader from '../layout/api-header.vue'

import CodeEditor from '@/component/code-editor.vue'

export default {

  components: { ApiLog, ApiPortal, NavMenu, ApiItem, ApiConfig, ApiDoc, ApiHeader, CodeEditor },

  data() {
    return {

      formSaving: false,

      appId: '',

      formValue: {
        'appSecret': ''
      },
      codeForm: {},

      apiChoose: {},

      rules: {
        appName: [
          { required: true, message: '请输入应用名称', trigger: 'blur' }
        ],
        // appType: [
        //   {required: true, message: '请输入应用类型', trigger: 'blur'}
        // ],
        callbackUrl: [
          { required: true, message: '请输入通信地址', trigger: 'blur' }
        ]
      },

      erpGroups: [],
      wmsGroups: [],


      apiRoot: []

    };
  },

  watch: {
    'formValue.openAppType'(val, old) {
      if (val == 'ERP') {
        this.apiRoot = this.erpGroups
      }
      else if (val == 'WMS') {
        this.apiRoot = this.wmsGroups
      }
      else {
        this.apiRoot = []
      }
    }
  },

  created() {
    let _this = this


    let formId = this.$route.query.id

    _this.formId = formId

    if (!_this.formId) {
      _this.generateRandomId();
      _this.generateRandomSecret()
    }
    _this.loadAllApis()

  },

  mounted() {
    var _this = this;

  },

  destroyed() {
  },

  methods: {

    generateRandomId() {
      let _this = this
      _this.$ajax({
        url: $portal_context + '/open/OpenApiConfigRpc/getRandomId.json',
        success: function (res) {
          if (res && res.data) {
            _this.appId = res.data
          }
        }
      })
    },

    generateRandomSecret() {
      let tmps = '01234567890abcdefghijklmnopqrstuvwxyz'
      let len = 32
      let output = ''
      for (let i = 0; i < len; i++) {
        let index = parseInt(Math.random() * tmps.length)
        output += tmps.substring(index, index + 1)
      }
      this.formValue.appSecret = output
      this.$message({
        type: 'info',
        message: 'appSecret 已重新生成，保存后生效'
      })
    },

    submitForm() {

      let _this = this

      _this.$refs['formEl'].validate((valid) => {
        if (valid) {

          _this.$ajax({
            url: '/open-api/open/OpenAppRpc/saveUpdateApp.json',
            type: 'json',
            data: _this.formValue,
            success: (responseData) => {
              this.$message({
                showClose: true,
                message: '提交成功',
                type: 'success'
              })
              _this.$jump('/app_info')

            }
          });

        } else {
          return false;
        }

      });

    },

    initCheckForms(docs, checkedMap) {

      let _this = this

      _this.erpGroups = docs.ERP
      _this.wmsGroups = docs.WMS

      _this.erpGroups.forEach(group => {
        group.children.forEach(c => {
          c._checked_ = checkedMap[c.apiUrl] ? true : false
        })
      })
      _this.wmsGroups.forEach(group => {
        group.children.forEach(c => {
          c._checked_ = checkedMap[c.apiUrl] ? true : false
        })
      })

    },

    loadAllApis() {

      let _this = this

      _this.$getAllDocs(function (docsResults) {

        if (_this.formId) {
          _this.$ajax({
            url: '/open-api/open/OpenApiConfigRpc/getAppDetail.json?id=' + _this.formId,
            success: function (res) {

              let checkedMap = {}
              if (res && res.data) {
                _this.formValue = res.data
                _this.appId = _this.formValue.appId

                if (_this.formValue.apiUrls) {
                  _this.formValue.apiUrls.forEach(tmpUri => {
                    checkedMap[tmpUri] = true
                  })
                }
              }
              _this.initCheckForms(docsResults, checkedMap)
            }
          })

        } else {
          _this.initCheckForms(docsResults, {})
        }

      })

    },


  }
}

</script>
<style>
.db_clear_list .el-checkbox {
  width: 600px;
  line-height: 30px;
}

.resource-div-block {
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  align-items: center;
}

.resource-div-block div {
  padding: 14px 40px 14px 40px;
  margin-bottom: 14px;
  font-size: 28px;
  color: #409eff;
  background: #ecf5ff;
  border-color: #b3d8ff;
  margin-right: 20px;
  cursor: pointer;
  position: relative;
}

.api-choose-table {
  background-color: #ececec;
  width: 100%;
}

.api-choose-table td {
  background-color: #fff;
  padding: 0px 8px 0px 8px;
  line-height: 42px;
}

.api-choose-table .choose-table-group-td {
  vertical-align: top;
  width: 140px;
}

.api-choose-table .choose-table-api-td {
  display: flex;
  justify-content: space-between;
}

.api-notify-tag {
  background-color: #fff;
  color: #81b1ff;
  border: 1px solid #81b1ff;
  border-radius: 4px;
  padding: 0px 2px;
}

.api-choose-label .el-form-item__label {
  padding-top: 5px;
}

.active-div {}

.unactive-div {
  color: #999;
}
</style>
